package com.hyw.encryption.utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.TimeZone;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * 新增JSON转换工具类
 * 
 * @author Hongyu
 */
public final class JsonUtils {
  private static final ObjectMapper objectMapper = new ObjectMapper();
  static {
    objectMapper.setSerializationInclusion(Include.NON_NULL);
    objectMapper.setTimeZone(TimeZone.getTimeZone("Asia/Chongqing"));
    objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
    objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
  }

  public static String toJsonString(Object obj) {
    try {
      return objectMapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
      throw new IllegalArgumentException(e);
    }
  }

  public static byte[] toJsonBytes(Object obj) {
    try {
      return objectMapper.writeValueAsBytes(obj);
    } catch (JsonProcessingException e) {
      throw new IllegalArgumentException(e);
    }
  }

  public static <T> T parseJson(Map<String, ?> param, Class<T> clz) {
    try {
      return objectMapper.readValue(objectMapper.writeValueAsString(param), clz);
    } catch (IOException e) {
      throw new IllegalArgumentException(e);
    }
  }

  public static <T> T parseJson(String json, Class<T> clz) {
    try {
      return objectMapper.readValue(json, clz);
    } catch (IOException e) {
      throw new IllegalArgumentException(e);
    }
  }

  @SuppressWarnings({ "rawtypes" })
  public static <T> T parseJson(String json, TypeReference valueTypeRef) {
    try {
      return (T) objectMapper.readValue(json, valueTypeRef);
    } catch (IOException e) {
      throw new IllegalArgumentException(e);
    }
  }

}
